package com.yanq.liancar.activity;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.adapter.Call;
import com.lzy.okgo.callback.BitmapCallback;
import com.lzy.okgo.callback.FileCallback;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Progress;
import com.lzy.okgo.model.Response;
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX;
import com.tencent.mm.opensdk.modelmsg.WXImageObject;
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.vondear.rxtool.RxActivityTool;
import com.vondear.rxtool.view.RxToast;
import com.yanq.liancar.R;
import com.yanq.liancar.activity.base.BaseToolbarActivity;
import com.yanq.liancar.adapter.ServiceTypeAdapter;
import com.yanq.liancar.adapter.ShopDetailsListAdapter;
import com.yanq.liancar.bean.BaseBean;
import com.yanq.liancar.bean.ShopEvaluateBean;
import com.yanq.liancar.bean.UserBean;
import com.yanq.liancar.url.Config;
import com.yanq.liancar.util.LogUtils;
import com.yanq.liancar.util.MyUtils;
import com.yanq.liancar.util.ToastUtil;
import com.yanq.liancar.util.Utils;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class ShopDetailsActivity extends BaseToolbarActivity {
    @BindView(R.id.img_phone)
    ImageView imgPhone;
    @BindView(R.id.img_map)
    ImageView imgMap;
    @BindView(R.id.img_youhuijuan)
    ImageView imgYouhuijuan;
    @BindView(R.id.img_guanzhu)
    ImageView imgGuanzhu;
    @BindView(R.id.img_fenxiang)
    ImageView imgFenxiang;
    @BindView(R.id.img_back)
    ImageView imgBack;
    @BindView(R.id.tv_comment)
    TextView tvComment;
    @BindView(R.id.comment_recyclerview)
    RecyclerView commentRecyclerview;
    @BindView(R.id.tv_shopName)
    TextView tvShopName;
    @BindView(R.id.tv_shop_address)
    TextView tvShopAddress;
    @BindView(R.id.tv_jianjie)
    TextView tvJianjie;
    @BindView(R.id.gridview_service)
    GridView gridview_service;

    private ShopDetailsListAdapter adapter;
    private ServiceTypeAdapter typeAdapter;
    private int shopID;
    private ShopEvaluateBean shopEvaluateBean = new ShopEvaluateBean();
    private ShopEvaluateBean.DataBean dataBean = new ShopEvaluateBean.DataBean();
    private List<ShopEvaluateBean.DataBean.RcsBean> rcsBeanList = new ArrayList<>();
    private static final String APP_ID = "wxd2e19fc6b6f17ec0"; //这个APP_ID就是注册APP的时候生成的
    private static final String APP_SECRET = "25a4d37924d1e69a753ac417551b627e";
    public IWXAPI api;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Utils.setStatusBar(this, false, true);
        setContentView(R.layout.activity_shopdetails);
        ButterKnife.bind(this);

        api = WXAPIFactory.createWXAPI(this, APP_ID, true);
        api.registerApp(APP_ID);

        shopID = getIntent().getIntExtra("shopId", 0);
        LogUtils.e("shopId", shopID + "");
        initRecyclerview();

        initData();
    }

    private void initData() {
        OkGo.<String>post(Config.s + "llc/shop/showAllShopDetailById")
                .tag(this)
                .params("id", shopID)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        Gson gson = new Gson();
                        shopEvaluateBean = gson.fromJson(response.body(), ShopEvaluateBean.class);
                        if (shopEvaluateBean.isIsSuccess()) {
                            dataBean = shopEvaluateBean.getData();
                            tvShopName.setText(dataBean.getShopName());
                            tvShopAddress.setText(dataBean.getShopAddress());
                            tvJianjie.setText(dataBean.getShopMsg());
                            initGridView();
                            rcsBeanList = dataBean.getRcs();
                            adapter.setNewData(rcsBeanList);
                        } else {
                            RxToast.error(shopEvaluateBean.getOutputMessage());
                        }
                    }

                });
    }

    private void initRecyclerview() {
        commentRecyclerview.setNestedScrollingEnabled(false);
        commentRecyclerview.setLayoutManager(new LinearLayoutManager(mContext));
        adapter = new ShopDetailsListAdapter(R.layout.item_small_c_shopedetails, rcsBeanList);
        commentRecyclerview.setAdapter(adapter);
        adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                //                Bundle bundle = new Bundle();
                //                bundle.putInt("Id", mList.get(position).id);
                //                bundle.putInt("auditStatus", auditStatus);
                //                readyGo(ApplyDetailsActivity.class, bundle);
            }
        });
    }

    private void initGridView() {
        //服务类型 1，精致洗车  2，标准洗车  3，美容养护，4,到店保养 5,钣金喷漆  6，代办服务   7,全车打蜡
        typeAdapter = new ServiceTypeAdapter(ShopDetailsActivity.this, dataBean.getAllType());
        gridview_service.setAdapter(typeAdapter);
        gridview_service.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if ("".equals(UserBean.getcToken(ShopDetailsActivity.this)) || TextUtils.isEmpty(UserBean.getcToken(ShopDetailsActivity.this))) {
                    RxToast.error("请先登录");
                } else {
                    LogUtils.e("adasdasda", dataBean.getAllType().get(position) + "");
                    if (dataBean.getAllType().get(position) == 1) {   //精准洗车
                        Bundle bundle = new Bundle();
                        bundle.putString("id", dataBean.getId() + "");
                        RxActivityTool.skipActivity(mContext, DelicateCarWashContentActivity.class, bundle);
                    } else if (dataBean.getAllType().get(position) == 2) {      //标准洗车
                        Bundle bundle = new Bundle();
                        bundle.putInt("type", 2);
                        bundle.putString("id", dataBean.getId() + "");
                        RxActivityTool.skipActivity(mContext, BuyStandardCarWashActivity.class, bundle);
                    } else if (dataBean.getAllType().get(position) == 3) {      //3，美容养护
                        Bundle bundle = new Bundle();
                        bundle.putInt("id", dataBean.getId());
                        bundle.putInt("type", 3);
                        RxActivityTool.skipActivity(ShopDetailsActivity.this, LacquerReservationActivity.class, bundle);
                    } else if (dataBean.getAllType().get(position) == 4) {      //4,到店保养
                        Bundle bundle = new Bundle();
                        bundle.putInt("id", dataBean.getId());
                        bundle.putInt("type", 4);
                        RxActivityTool.skipActivity(ShopDetailsActivity.this, LacquerReservationActivity.class, bundle);
                    } else if (dataBean.getAllType().get(position) == 5) {      //5,钣金喷漆
                        Bundle bundle = new Bundle();
                        bundle.putInt("id", dataBean.getId());
                        bundle.putInt("type", 5);
                        RxActivityTool.skipActivity(ShopDetailsActivity.this, LacquerReservationActivity.class, bundle);
                    } else if (dataBean.getAllType().get(position) == 6) {      //6，代办服务
                        //                        Bundle bundle = new Bundle();
                        //                        bundle.putInt("id", dataBean.getId());
                        //                        RxActivityTool.skipActivity(mContext, AgencyServiceActivity.class, bundle);
                        RxToast.error("该服务暂未开放");
                    } else if (dataBean.getAllType().get(position) == 7) {        //7 全车打蜡
                        Bundle bundle = new Bundle();
                        bundle.putInt("id", dataBean.getId());
                        bundle.putInt("type", 7);
                        RxActivityTool.skipActivity(ShopDetailsActivity.this, LacquerReservationActivity.class, bundle);
                    }
                }
            }
        });
    }


    @OnClick({R.id.img_phone, R.id.img_map, R.id.img_youhuijuan, R.id.img_guanzhu, R.id.img_fenxiang, R.id.img_back, R.id.tv_comment})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.img_phone:
                Intent intent = new Intent(Intent.ACTION_CALL);
                Uri data = Uri.parse("tel:" + shopEvaluateBean.getData().getShopTel());
                intent.setData(data);
                if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
                    // TODO: Consider calling
                    //    ActivityCompat#requestPermissions
                    // here to request the missing permissions, and then overriding
                    //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                    //                                          int[] grantResults)
                    // to handle the case where the user grants the permission. See the documentation
                    // for ActivityCompat#requestPermissions for more details.
                    return;
                }
                startActivity(intent);

                break;
            case R.id.img_map:
                if (shopEvaluateBean != null) {
                    Bundle bundle = new Bundle();
                    bundle.putString("logo", shopEvaluateBean.getData().getShopPages().get(0).getWebPath());
                    bundle.putString("title", shopEvaluateBean.getData().getShopName());
                    bundle.putString("address", shopEvaluateBean.getData().getShopAddress());
                    bundle.putString("pinglun", shopEvaluateBean.getData().getRamarkNum());
                    bundle.putString("shoucang", shopEvaluateBean.getData().getAttenNum());
                    bundle.putDouble("jing", shopEvaluateBean.getData().getLat());
                    bundle.putDouble("wei", shopEvaluateBean.getData().getLon());
                    RxActivityTool.skipActivity(this, ShopLocationActivity.class, bundle);
                }
                break;
            case R.id.img_youhuijuan:
                break;
            case R.id.img_guanzhu:
                guanzhu();
                break;
            case R.id.img_fenxiang:
                ToastUtil.showProgressDialog(this);
                downLodeFile(shopEvaluateBean.getData().getShopPages().get(0).getWebPath());
                break;
            case R.id.img_back:
                finish();
                break;
            case R.id.tv_comment:
                Bundle bundle=new Bundle();
                bundle.putString("shopID",shopID+"");
                RxActivityTool.skipActivity(mContext, ShopCommentActivity.class,bundle);
                break;
        }
    }

    private void guanzhu() {
        OkGo.<String>post(Config.s + "llc/attenShopController/attenShop")
                .tag(this)
                .params("sid", shopID)
                .params("token", UserBean.getcToken(this))
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        Gson gson = new Gson();
                        BaseBean baseBean = gson.fromJson(response.body(), BaseBean.class);
                        if (baseBean.isIsSuccess()) {
                            RxToast.success(baseBean.getOutputMessage());
                        } else {
                            RxToast.error(baseBean.getOutputMessage());
                        }
                    }

                });
    }

    private void downLodeFile(String url) {
        OkGo.<Bitmap>get(url)//
                .tag(this)//
                .execute(new BitmapCallback() {
                    @Override
                    public void onSuccess(Response<Bitmap> response) {
                        ToastUtil.dismissProgressDialog();
                        sharePicByFile(response.body(),"ShopDetailsActivity");
                    }

                    @Override
                    public void onError(Response<Bitmap> response) {
                        ToastUtil.dismissProgressDialog();
                        RxToast.error("分享失败");
                    }
                });

    }

    public void sharePicByFile(Bitmap pic, String tag) {

        WXImageObject imageObject = new WXImageObject(pic);

        //这个构造方法中自动把传入的bitmap转化为2进制数据,或者你直接传入byte[]也行
        // 注意传入的数据不能大于10M,开发文档上写的
        WXMediaMessage msg = new WXMediaMessage();
        // 这个对象是用来包裹发送信息的对象
        msg.mediaObject = imageObject;
        // msg.mediaObject实际上是个IMediaObject对象,
        // 它有很多实现类,每一种实现类对应一种发送的信息,
        // 比如WXTextObject对应发送的信息是文字,想要发送文字直接传入WXTextObject对象就行
        Bitmap thumbBitmap = Bitmap.createScaledBitmap(pic, 150, 150, true);
        //msg.thumbData = bitmap2ByteArray(thumbBitmap);
        msg.setThumbImage(thumbBitmap);
        //在这设置缩略图
        // 官方文档介绍这个bitmap不能超过32kb
        // 如果一个像素是8bit的话换算成正方形的bitmap则边长不超过181像素,边长设置成150是比较保险的
        // 或者使用msg.setThumbImage(thumbBitmap);省去自己转换二进制数据的过程
        // 如果超过32kb则抛异常
        SendMessageToWX.Req req = new SendMessageToWX.Req();
        // 创建一个请求对象
        req.message = msg;
        // 把msg放入请求对象中
        req.scene = SendMessageToWX.Req.WXSceneTimeline;
        // 设置发送到朋友圈
        req.scene = SendMessageToWX.Req.WXSceneSession;
        // 设置发送给朋友
        req.transaction = tag;
        // 这个tag要唯一,用于在回调中分辨是哪个分享请求
        boolean b = api.sendReq(req);
        // 如果调用成功微信,会返回true
        //
    }


}
